//
//  AccountController.swift
//  账号界面
//
//  Created by smile on 2019/4/11.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//主题框架
import SwiftTheme

//日志框架
import CocoaLumberjack

//发布订阅框架
import SwiftEventBus

class AccountController: BaseTitleController {

    //日志TAG
    private static let TAG="AccountController"
    
    /// 用户信息容器
    @IBOutlet weak var svUserInfo: UIStackView!
    
    /// 头像控件
    @IBOutlet weak var ivAvatar: UIImageView!
    
    /// 昵称控件
    @IBOutlet weak var lbNickname: UILabel!
    
    /// 个人描述控件
    @IBOutlet weak var lbDescription: UILabel!
    
    /// 签到按钮
    @IBOutlet weak var btSignIn: UIButton!
    
    /// 动态数
    @IBOutlet weak var lbFeedCount: UILabel!
    
    /// 朋友数
    @IBOutlet weak var lbFriendCount: UILabel!
    
    /// 粉丝数
    @IBOutlet weak var lbFansCount: UILabel!
    
    /// 编辑用户信息按钮
    @IBOutlet weak var btEditProfile: UIButton!
    
    /// 用户好友点击容器
    @IBOutlet weak var svFriend: UIStackView!
    
    /// 用户粉丝点击容器
    @IBOutlet weak var svFans: UIStackView!
    
    /// 我的二维码容器
    @IBOutlet weak var svCode: UIStackView!
    
    /// 我的消息容器
    @IBOutlet weak var svMessage: UIStackView!
    
    /// 商城容器
    @IBOutlet weak var svShop: UIStackView!
    
    /// 我的订单容器
    @IBOutlet weak var svOrder: UIStackView!
    
    /// 我的订单容器（接口数据加密）
    @IBOutlet weak var svNewOrder: UIStackView!
    
    /// 设置容器
    @IBOutlet weak var svSettings: UIStackView!
    
    /// 夜间模式
    @IBOutlet weak var stNight: UISwitch!
    
    /// 定义关闭容器
    @IBOutlet weak var svTimeClose: UIStackView!
    
    /// 我的消息图标
    @IBOutlet weak var ivMessageIcon: UIImageView!
    
    /// 我的消息容器
    @IBOutlet weak var lbMessage: UILabel!
    
    /// 关于我们容器
    @IBOutlet weak var svAbout: UIStackView!
    
    /// 关于我们（代码自动布局）
    @IBOutlet weak var svAboutCode: UIStackView!
    
    /// 关于我们（其他storyboard）
    @IBOutlet weak var svAboutOther: UIStackView!
    
    /// 显示未读消息红点
    private var hub:RKNotificationHub!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func initViews() {
        super.initViews()
        
        DDLogWarn("AccountController initViews")
        
        DDLogWarn("initViews",tag: AccountController.TAG)
        
        setTitle("账号")
        
        //头像显示圆角
        ViewUtil.showRadius(ivAvatar, 30)
        
        //测试主题框架
        lbNickname.theme_textColor=["#000", "#F00"]
        
        //签到按钮显示边框
        btSignIn.showColorPrimaryBorder()
        
        //签到按钮显示圆角
        ViewUtil.showRadius(btSignIn, 15)
        
        //显示红点View
        hub = RKNotificationHub(view: lbMessage)
        
        //绝对位置
//        hub.setCircleAtFrame(CGRect(x: -10, y: -10, width: 30, height: 30))
        
        //设置相对偏移位置
//        hub.moveCircleBy(x: -100, y: 0)
        
        //设置大小
        //原来大小的倍数
        hub.scaleCircleSize(by: 0.8)
        
        //从偏好设置中恢复状态
        stNight.setOn(PreferenceUtil.isNight(), animated: true)
    }
    
    override func initDatas() {
        super.initDatas()
        
        DDLogWarn("AccountController initDatas")
        
        DDLogWarn("initDatas",tag: AccountController.TAG)
        
        fetchData()
    }
    
    func fetchData() {
        Api.shared
            .userDetail(PreferenceUtil.userId()!)
            .subscribeOnSuccess { (data) in
                if let data = data?.data {
                    self.showData(data)
                }
        }.disposed(by: disposeBag)
        
    }
    
    func showData(_ data:User) {
        print("AccountController show user detail:\(data.nickname!)")
        
        //显示头像
        ImageUtil.showAvatar(ivAvatar, data.avatar)
        
        //显示昵称
        lbNickname.text=data.nickname
        
        //显示描述
        lbDescription.text=data.formatDescription
        
        //好友数
        lbFriendCount.text="\(data.followings_count)"
        
        //粉丝数
        lbFansCount.text="\(data.followers_count)"
        
    }

    override func initListeners() {
        super.initListeners()
        
        DDLogVerbose("AccountController initListeners")
        
        //用户信息部分点击
        svUserInfo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onUserInfoClick)))
        
        //好友列表点击
        svFriend.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onFriendClick)))
        
        //粉丝列表点击
        svFans.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onFansClick)))
        
        //我的二维码点击
        svCode.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onCodeClick)))
        
        //我的消息点击
        svMessage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onMessageClick)))
        
        //商城点击
        svShop.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onShopClick)))
        
        //订单点击
        svOrder.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onOrderClick)))
        
        //新订单点击
        //主要是演示接口签名和加密
        svNewOrder.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onNewOrderClick)))
        
        //设置点击
        svSettings.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onSettingClick)))
        
        
        //关于爱学啊（可视化布局）点击
        svAbout.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutClick)))
        
        //关于爱学啊（代码自动布局）点击
        svAboutCode.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutCodeClick)))
        
        //关于爱学啊（其他storyboard）点击
        svAboutOther.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutOtherClick)))
        
        //监听更新了用户信息
        SwiftEventBus.onMainThread(self, name: ON_UPDATE_USER_INFO) { result in
            //重新获取用户信息
            self.fetchData()
        }
        
    }

    
    /// 用户信息部分点击
    @objc func onUserInfoClick() {
        print("AccountController onUserInfoClick")
        UserDetailController.start(navigationController!, userId: PreferenceUtil.userId()!)
    }
    
    /// 好友列表点击
    @objc func onFriendClick() {
        print("AccountController onFriendClick")
        UserController.start(navigationController!, PreferenceUtil.userId()!, .friend)
    }
    
    /// 粉丝列表点击
    @objc func onFansClick() {
        print("AccountController onFansClick")
        UserController.start(navigationController!, PreferenceUtil.userId()!, .fans)
    }
    
    /// 我的二维码点击
    @objc func onCodeClick() {
        print("AccountController onCodeClick")
        MyCodeController.start(navigationController!)
    }
    
    /// 我的消息点击
    @objc func onMessageClick() {
        print("AccountController onMessageClick")
        MessageController.start(navigationController!)
        
        //和这个用户聊天
//        ChatController.start(navigationController!,"20")
    }
    
    
    /// 商城点击
    @objc func onShopClick() {
        print("AccountController onShopClick")
        ShopController.start(navigationController!)
    }
    
    /// 订单点击
    @objc func onOrderClick() {
        print("AccountController onOrderClick")
        OrderController.start(navigationController!)
    }
    
    /// 新订单点击
    /// 主要是演示接口签名和加密
    @objc func onNewOrderClick() {
        print("AccountController onNewOrderClick")
        NewOrderController.start(navigationController!)
    }
    
    /// 设置点击
    @objc func onSettingClick() {
        print("AccountController onSettingClick")
        SettingController.start(navigationController!)
    }
    
    //关于爱学啊（可视化布局）点击
    @objc func onAboutClick() {
        print("AccountController onAboutClick")
        AboutController.start(navigationController!)
    }
    
    //关于爱学啊（代码自动布局）点击
    @objc func onAboutCodeClick() {
        print("AccountController onAboutCodeClick")
        AboutCodeController.start(navigationController!)
    }
    
    //关于爱学啊（其他storyboard）点击
    @objc func onAboutOtherClick() {
        print("AccountController onAboutOtherClick")
        AboutOtherController.start(navigationController!)
    }
    
    /// 退出按钮点击事件
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onLogoutClick(_ sender: Any) {
        print("AccountController onLogoutClick")
        
        //添加一个弹窗
        //因为我们本质想留住用户
        let alertController = UIAlertController(title: "提示", message: "你确定退出吗？", preferredStyle: .alert)
        
        //确定点击回调
        let confirmAction = UIAlertAction(title: "确定", style: .default) { (action) in
            AppDelegate.shared.logout()
        }
        
        //取消点击回调
        let cancelAction = UIAlertAction(title: "取消", style: .default, handler: nil)
        
        //将这两个动作添加到控制器中
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
        
        //显示这个弹窗
        present(alertController, animated: true, completion: nil)
        
    }
    
    /// 日间/夜间模式切换回调
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onNightChanged(_ sender: UISwitch) {
        //调用AppDelegate中设置夜间模式的方法
        AppDelegate.shared.setNight(sender.isOn)
        
        //将值设置到偏好设置
        PreferenceUtil.setNight(sender.isOn)
    }
    
    /// 视图已经可见了
    ///
    /// - Parameter animated: <#animated description#>
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        updateMessageReadCount()
        
        //监听消息
        JMessage.add(self, with: nil)
        
        //使用极光分析
        //统计页面
        JANALYTICSService.startLogPageView("Account")
    }
    
    /// 视图已经消失
    ///
    /// - Parameter animated: animated description
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        //界面不可见
        //移除监听
        //可以提高效率
        JMessage.remove(self, with: nil)
    }
    
    //刷新消息未读数
    //如果有就显示红点
    func updateMessageReadCount() {
        let unreadMessageCountInt=MessageUtil.getUnreadMessageCount()
        if unreadMessageCountInt>0 {
            //有未读消息
            hub.count=Int32(unreadMessageCountInt)
            hub.pop()
        }else{
            hub.count=0
        }
    }
    
    /// 二维码扫描点击事件
    ///
    /// - Parameter sender: sender description
    @IBAction func onScanClick(_ sender: UIBarButtonItem) {
        print("AccountController onScanClick")
        
        ScanController.start(navigationController!)
    }
    
    
    /// 编辑用户资料点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onEditProfileClick(_ sender: Any) {
        print("AccountController onEditProfileClick")
        
        ProfileController.start(navigationController!)
    }

}

// MARK: - 极光聊天消息代理
extension AccountController:JMessageDelegate {
    //极光聊天在线消息回调
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        updateMessageReadCount()
    }
}
